package com.ruoyi.biz.imported.strategy;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Validator;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ruoyi.biz.imported.vo.ReqVO;
import com.ruoyi.biz.letter.domain.BizCityLetter;
import com.ruoyi.biz.letter.export.BizCityLetterExport;
import com.ruoyi.biz.letter.mapper.BizCityLetterMapper;
import com.ruoyi.biz.plan.domain.BizPlanConfig;
import com.ruoyi.biz.plan.enums.PlanType;
import com.ruoyi.biz.plan.enums.SourceType;
import com.ruoyi.biz.plan.mapper.BizPlanConfigMapper;
import com.ruoyi.biz.plan.service.IBizPlanConfigService;
import com.ruoyi.common.enums.LetterStatus;
import com.ruoyi.common.enums.UserStatus;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author Fei.Cong
 * @date 2024-07-17 14:08
 */
@Slf4j
@Service
public class DispatchStrategy implements ImportedStrategy {

    @Autowired
    private BizCityLetterMapper bizCityLetterMapper;

    @Autowired
    private IBizPlanConfigService bizPlanConfigService;

    @SneakyThrows
    @Override
    public String importHandleData(ReqVO reqVO) {

        ExcelUtil<BizCityLetterExport> util = new ExcelUtil<BizCityLetterExport>(BizCityLetterExport.class);
        List<BizCityLetterExport> citySheet1List = util.importEasyExcel(reqVO.getFile().getInputStream(), 0, 2);
        List<BizCityLetterExport> citySheet2List = util.importEasyExcel(reqVO.getFile().getInputStream(), 1, 2);
//        if (CollectionUtil.isEmpty(citySheet1List)) {
        if (CollectionUtil.isEmpty(citySheet1List) && CollectionUtil.isEmpty(citySheet2List)) {
            throw new ServiceException("导入数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        citySheet1List.addAll(citySheet2List);

        Set<String> billMonths = citySheet1List.stream().map(v -> DateUtil.format(v.getLetterTime(), "yyyy-MM")).collect(Collectors.toSet());
        BizPlanConfig planConfig = new BizPlanConfig();
        planConfig.setBillMonths(billMonths);
        planConfig.setSource(SourceType.CITY_DATA.getCode());
        planConfig.setType(PlanType.DISPATCH.getCode());
        bizPlanConfigService.checkPlan(planConfig);

        StringBuilder msg = new StringBuilder();

        if (!reqVO.isUpdateSupport()) {
            for (BizCityLetterExport cityLetter : citySheet1List) {
                try {
                    if (StrUtil.isBlank(cityLetter.getLetterNumber())) {
                        continue;
                    }
                    BizCityLetter entity = bizCityLetterMapper.selectOne(new LambdaQueryWrapper<BizCityLetter>().eq(BizCityLetter::getLetterNumber, cityLetter.getLetterNumber()));
                    if (Objects.isNull(entity)) {
                        failureNum++;
                        msg.append("<br/>" + failureNum + "、信访件编号 " + cityLetter.getLetterNumber() + " <font style='color:#E6A23C'>原数据未导入</font>");
                        continue;
                    }
                    if (Objects.nonNull(cityLetter.getIsFinish()) || Objects.nonNull(cityLetter.getIsSolve())) {
                        successNum++;
                        msg.append("<br/>" + successNum + "、信访件编号 " + cityLetter.getLetterNumber() + " <font style='color:#67C23A'>调度成功</font>");
                        entity.setIsSolve(cityLetter.getIsSolve());
                        entity.setIsFinish(cityLetter.getIsFinish());
                        entity.setIsLaw(cityLetter.getIsLaw());
                        entity.setDispatchBy(SecurityUtils.getUsername());
                        entity.setDispatchTime(new Date());
                        entity.setStatus(LetterStatus.DISPATCH_SUCCESS.getCode());
                        bizCityLetterMapper.updateById(entity);
                    } else {
                        failureNum++;
                        msg.append("<br/>" + failureNum + "、信访件编号 " + cityLetter.getLetterNumber() + " <font style='color:#E6A23C'>未处理</font>");
                    }
                } catch (Exception e) {
                    failureNum++;
                    String emsg = "<br/>" + failureNum + "、信访件编号 " + cityLetter.getLetterNumber() + " 导入失败：";
                    msg.append(emsg + e.getMessage());
                    log.error(emsg, e);
                }
            }
        }

        msg.insert(0, "操作成功！成功 " + successNum + " 条，失败 " + failureNum + " 条，数据如下：");

        return msg.toString();
    }
}
